package com.piece.blog.controller;

import com.piece.blog.model.TrainingResource;
import com.piece.blog.service.TrainingResourceService;
import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.support.bootstrap.DataTable;
import com.piece.core.framework.support.bootstrap.QueryTable;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.log.config.UserContextHolder;
import com.piece.core.web.controller.FrameWorkController;
import com.piece.file.model.TbSysFile;
import com.piece.file.service.TbSysFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 资源Controller
 *
 * @author onepiece
 * @date 2023-08-29
 */
@RestController
@Api(tags = {"资源管理"})
@RequestMapping("/api/training/resource")
public class TrainingResourceController extends FrameWorkController {

    @Resource
    private TrainingResourceService trainingResourceService;

    @Resource
    private TbSysFileService tbSysFileService;

    @PostMapping("/list")
    @AclPermission(code = "training:resource:view")
    @ApiOperation(value = "查询资源列表")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public List list() {
        QueryTable queryTable = initTable();
        DataTable dataTable = trainingResourceService.findPage(queryTable);
        return dataTable.getData();
    }

    @PostMapping("/table")
    @AclPermission(code = "training:resource:view")
    @ApiOperation(value = "查询资源分页数据")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse table() {
        QueryTable queryTable = initTable();
        DataTable dataTable = trainingResourceService.findPage(queryTable);
        return success(dataTable);
    }

    @GetMapping("/load")
    @AclPermission(code = "training:resource:view")
    @ApiOperation(value = "加载资源表单数据")
    @ApiImplicitParam(name="id", value = "主键")
    public AjaxResponse load() {
        long id = Convert.toLong(getRequest().getParameter("id"), 0L);
        TrainingResource trainingResource = new TrainingResource();
        if (id != 0) {
            trainingResource = trainingResourceService.findById(id);
        }
        if (null != trainingResource.getFileId()) {
            TbSysFile file = tbSysFileService.findById(trainingResource.getFileId() + "");
            if (null != file) {
                trainingResource.setFileName(file.getOriginalFilename());
            }
        }
        return success(trainingResource);
    }

    @SubmitPermission
    @PostMapping("/save")
    @AclPermission(code = "training:resource:edit")
    @ApiOperation(value = "保存资源表单数据")
    @ApiImplicitParam(value = "资源数据", dataTypeClass = TrainingResource.class, type = "body")
    public AjaxResponse save() {
        TrainingResource trainingResource;
        try {
            Long id = Convert.toLong(getRequest().getParameter("resourceId"));
            if (null != id) {
                trainingResource = trainingResourceService.findById(id);
            } else {
                trainingResource = new TrainingResource();
                trainingResource.setCreateBy(Convert.toLong(UserContextHolder.getUserId()));
                trainingResource.setCreateTime(new Date());
            }
            initDB(trainingResource);
            trainingResourceService.insertOrUpdate(trainingResource);

            if (StringUtil.isNotEmpty(trainingResource.getFileId())) {
                // 重新设置文件后缀、大小、时长
                TbSysFile file = tbSysFileService.findById(trainingResource.getFileId() + "");
                file.setBusinessId(trainingResource.getResourceId() + "");
                file.setTable(trainingResource.getClass().getSimpleName());
                trainingResource.setExtension(file.getContentType());
                trainingResource.setSize(file.getFileSize());
                trainingResource.setDuration(file.getDuration());
                tbSysFileService.update(file);
            }

            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/delete/{id}")
    @AclPermission(code = "training:resource:delete")
    @ApiOperation(value = "删除资源数据")
    @ApiImplicitParam(name = "id", value = "主键", type = "path")
    public AjaxResponse delete(@PathVariable String id) throws Exception {
        tbSysFileService.deleteByTableAndBusinessList(TrainingResource.class.getSimpleName(), Convert.toStrList(id));
        trainingResourceService.delete(id);
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @SubmitPermission
    @PostMapping("/delete")
    @AclPermission(code = "training:resource:delete")
    @ApiOperation(value = "删除资源数据")
    @ApiImplicitParam(name = "ids", value="主键集合")
    public AjaxResponse deleteBatch() throws Exception {
        String ids = getRequest().getParameter("ids");
        if (StringUtil.isNotEmpty(ids)) {
            tbSysFileService.deleteByTableAndBusinessList(TrainingResource.class.getSimpleName(), Convert.toStrList(ids));
            trainingResourceService.delete(Convert.toLongArray(ids));
        }
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

}
